<template>
    <view class="select-container" :style="{'--status-bar-height': statusBarHeight + 'px'}">
        <!-- 导航栏 -->
        <view class="nav-bar">
            <view class="back-icon" @click="goBack">
                <image src="/static/arrow-left.png" mode="aspectFit"></image>
            </view>
            <view class="title">选择页面</view>
        </view>

        <!-- 步骤指示器 -->
        <view class="step-indicator">
            <view class="step-item" v-for="(tab, index) in tabOrder" :key="index" :class="{
                'completed': getTabIndex(currentTab) > index,
                'active': getTabIndex(currentTab) === index
            }">
                <view class="step-dot"></view>
                <view class="step-line" v-if="index < tabOrder.length - 1"></view>
            </view>
        </view>

        <!-- 筛选标签 -->
        <view class="filter-tabs">
            <view class="tab-item" v-for="(_, tab) in options" :key="tab" :class="{ active: currentTab === tab }"
                @click="changeTab(tab)">
                {{ tab }}
            </view>
        </view>

        <!-- 主要内容 -->
        <view class="content" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
            <view class="question">想要把心意带给谁呢?</view>

            <!-- 已选择选项展示区域 -->
            <view class="selected-items" v-if="currentTab !== '价格' && selectedValues[currentTab].length > 0">
                <view class="selected-item" v-for="(item, index) in selectedValues[currentTab]" :key="index">
                    {{ item }}
                    <text class="remove-icon" @click="removeSelectedItem(item)">×</text>
                </view>
            </view>

            <!-- 选项 - 根据选项数量动态布局 -->
            <view class="options-container">
                <!-- 类型选项的分页控制器 -->
                <view class="page-controller" v-if="currentTab === '类型'">
                    <view class="page-btn prev" @click="prevTypePage" :class="{ disabled: currentTypePage === 1 }">
                        <image src="/static/arrow-left.png" mode="aspectFit" style="width: 24rpx;height: 16rpx;"></image>
                    </view>
                    <view class="page-indicator">{{ currentTypePage }}/{{ totalTypePages }}</view>
                    <view class="page-btn next" @click="nextTypePage" :class="{ disabled: currentTypePage === totalTypePages }">
                        <image src="/static/right.png" mode="aspectFit" style="width: 36rpx;height: 28rpx;"></image>
                    </view>
                </view>
                <!-- 单列布局 -->
                <block v-if="currentOptions.length <= 3">
                    <view class="option-row" v-for="(item, index) in currentOptions" :key="index">
                        <view class="option-item" 
                            :class="{ 
                                selected: currentTab === '价格' ? selectedValues[currentTab].includes(item) : selectedValues[currentTab].includes(item) 
                            }"
                            @click="selectItem(item)">{{ item }}</view>
                    </view>
                </block>

                <!-- 两列布局 -->
                <block v-else>
                    <view class="option-row two-columns" v-for="i in Math.ceil(currentOptions.length / 2)" :key="i">
                        <view class="option-item"
                            :class="{ 
                                selected: currentTab === '价格' ? 
                                    selectedValues[currentTab].includes(currentOptions[(i - 1) * 2]) : 
                                    selectedValues[currentTab].includes(currentOptions[(i - 1) * 2])
                            }"
                            @click="selectItem(currentOptions[(i - 1) * 2])">
                            {{ currentOptions[(i - 1) * 2] }}
                        </view>
                        <view class="option-item" v-if="(i - 1) * 2 + 1 < currentOptions.length"
                            :class="{ 
                                selected: currentTab === '价格' ? 
                                    selectedValues[currentTab].includes(currentOptions[(i - 1) * 2 + 1]) : 
                                    selectedValues[currentTab].includes(currentOptions[(i - 1) * 2 + 1])
                            }"
                            @click="selectItem(currentOptions[(i - 1) * 2 + 1])">
                            {{ currentOptions[(i - 1) * 2 + 1] }}
                        </view>
                    </view>
                </block>
            </view>
        </view>
        <!-- 全选操作区 -->
        <view class="select-all-btn" @click="selectAllItems">
            <!-- {{ isAllSelected ? '取消全选' : '全选' }} -->
              {{ '跳过当前筛选' }}
        </view>
        <!-- 底部操作区 -->
        <view class="bottom-actions">
            <view class="back-btn" @click="goPrevious">
                <image src="/static/zuo-bai.png" mode="aspectFit"></image>
            </view>
            <view class="skip-btn" @click="skip">跳过全部筛选</view>
            <view class="next-btn" @click="goNext">
                <image src="/static/you-bai.png" mode="aspectFit"></image>
            </view>
        </view>

        <!-- 进度条 -->
        <view class="progress-bar">
            <view class="progress-inner" :style="{ width: progressWidth + '%' }"></view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            statusBarHeight: 0, // Add status bar height property
            currentTab: '对象',
            swipeOffset: 0,
            isAnimating: false,
            touchStartX: null,
            selectedValues: {
                '对象': [],
                '场合': [],
                '性别': [],
                '类型': [],
                '年龄': [],
                '价格': []
            },
            currentTypePage: 1,
            typePageSize: 10,
            valueMapping: {
                对象: {
                    '父母': 'elder',
                    '朋友': 'friend',
                    '配偶': 'lover',
                    '儿童': 'children',
                    '亲戚': 'relative',
                    '同事': 'colleague',
                    '客户': 'client'
                },
                场合: {
                    '传统节日': 'traditional_festival',
                    '生日': 'birthday',
                    '纪念日': 'anniversary',
                    '毕业': 'graduation',
                    '乔迁': 'moving',
                    '平日/伴手礼': 'everyday_gift',
                    '父/母亲节': 'fm_festival',
                    '儿童节': 'children_day',
                    '纪念场合': 'com_occasions',
                    '商务': 'business'
                },
                性别: {
                    '男': 'male',
                    '女': 'female'
                },
                类型: {
                    '饰品': 'jewelry',
                    '生活': 'life',
                    '美妆护肤': 'skincare',
                    '美食': 'food',
                    '健康': 'health',
                    '文艺': 'art',
                    '趣味': 'fun',
                    '告白': 'confession',
                    '日常(小心意)': 'daily_gift',
                    '数码': 'digital',
                    '型男必备': 'men_essentials',
                    '精选礼盒': 'gift_box',
                    '摆件': 'ornament',
                    '茶酒': 'tea_wine',
                    '定制礼品': 'custom_gift',
                    '情侣款': 'couple',
                    '玩具': 'toy',
                    '图书绘本': 'book',
                    '科学益智': 'science_puzzle',
                    '玩偶': 'doll',
                    '爸爸的礼物精选': 'dad_gift',
                    '妈妈的礼物精选': 'mom_gift'
                },
                年龄: {
                    '0-12': 'age_0_12',
                    '12-18': 'age_12_18',
                    '18-35': 'age_18_35',
                    '35-45': 'age_35_45',
                    '45-60': 'age_45_60',
                    '60+': 'age_60_plus'
                },
                价格: {
                    '0-100': '0-100',
                    '100-300': '100-300',
                    '300-500': '300-500',
                    '500-1000': '500-1000',
                    '1000-1500': '1000-1500',
                    '1500-2000': '1500-2000',
                    '2000-2500': '2000-2500',
                    '2500-3000': '2500-3000',
                    '3000+': '>3000'
                }
            },
            options: {
                对象: ['父母', '朋友', '配偶', '儿童', '亲戚', '同事', '客户'],
                场合: ['传统节日', '生日', '纪念日', '毕业', '乔迁', '平日/伴手礼', '父/母亲节', '儿童节', '纪念场合', '商务'],
                性别: ['男', '女'],
                类型: ['饰品', '生活', '美妆护肤', '美食', '健康', '文艺', '趣味', '告白', '日常(小心意)', '数码', '型男必备', '精选礼盒', '摆件', '茶酒', '定制礼品', '情侣款', '玩具', '图书绘本', '科学益智', '玩偶', '爸爸的礼物精选', '妈妈的礼物精选'],
                年龄: ['0-12', '12-18', '18-35', '35-45', '45-60', '60+'],
                价格: ['0-100', '100-300', '300-500', '500-1000', '1000-1500', '1500-2000', '2000-2500', '2500-3000', '3000+']
            },
            tabOrder: ['对象', '场合', '性别', '类型', '年龄', '价格']
        }
    },
    onLoad() {
        // Get status bar height for different devices
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 0;
    },
    computed: {
        isAllSelected() {
            if (this.currentTab === '价格') return false;
            const currentOptions = this.options[this.currentTab];
            return currentOptions.every(item => this.selectedValues[this.currentTab].includes(item));
        },
        currentOptions() {
            if (this.currentTab === '类型') {
                const start = (this.currentTypePage - 1) * this.typePageSize;
                const end = start + this.typePageSize;
                return this.options[this.currentTab].slice(start, end);
            }
            return this.options[this.currentTab] || [];
        },
        totalTypePages() {
            if (this.currentTab === '类型') {
                return Math.ceil(this.options.类型.length / this.typePageSize);
            }
            return 1;
        },
        progressWidth() {
            const totalSteps = this.tabOrder.length;
            const currentStep = this.getTabIndex(this.currentTab) + 1;
            return (currentStep / totalSteps) * 100;
        }
    },
    methods: {
        getTabIndex(tab) {
            return this.tabOrder.indexOf(tab);
        },
        changeTab(tab) {
            this.currentTab = tab;
        },
        selectItem(item) {
            if (this.currentTab === '价格') {
                // 价格支持多选
                const index = this.selectedValues[this.currentTab].indexOf(item);
                if (index === -1) {
                    // 添加选项
                    this.selectedValues[this.currentTab].push(item);
                } else {
                    // 移除选项
                    this.selectedValues[this.currentTab].splice(index, 1);
                }
            } else {
                // 其他选项支持多选，切换选中状态
                const index = this.selectedValues[this.currentTab].indexOf(item);
                if (index === -1) {
                    // 添加选项
                    this.selectedValues[this.currentTab].push(item);
                } else {
                    // 移除选项
                    this.selectedValues[this.currentTab].splice(index, 1);
                }
            }
        },
        removeSelectedItem(item) {
            // 从已选中项中移除
            const index = this.selectedValues[this.currentTab].indexOf(item);
            if (index !== -1) {
                this.selectedValues[this.currentTab].splice(index, 1);
            }
        },
        goBack() {
            uni.navigateBack();
        },
        handleTouchStart(e) {
            if (this.currentTab !== '类型') return;
            this.touchStartX = e.touches[0].clientX;
            this.isAnimating = false;
        },
        handleTouchMove(e) {
            if (this.currentTab !== '类型' || !this.touchStartX) return;
            const currentX = e.touches[0].clientX;
            const diff = currentX - this.touchStartX;
            if ((this.currentTypePage === 1 && diff > 0) || 
                (this.currentTypePage === this.totalTypePages && diff < 0)) {
                this.swipeOffset = diff * 0.2;
            } else {
                this.swipeOffset = diff;
            }
        },
        handleTouchEnd() {
            if (this.currentTab !== '类型' || !this.touchStartX) return;
            this.touchStartX = null;
            this.isAnimating = true;
            const threshold = 50;
            
            if (Math.abs(this.swipeOffset) > threshold) {
                if (this.swipeOffset > 0 && this.currentTypePage > 1) {
                    this.prevTypePage();
                } else if (this.swipeOffset < 0 && this.currentTypePage < this.totalTypePages) {
                    this.nextTypePage();
                }
            }
            this.swipeOffset = 0;
        },
        nextTypePage() {
            if (this.currentTypePage < this.totalTypePages) {
                this.currentTypePage++;
            }
        },
        prevTypePage() {
            if (this.currentTypePage > 1) {
                this.currentTypePage--;
            }
        },
        goNext() {
            const currentIndex = this.getTabIndex(this.currentTab);

            if (currentIndex < this.tabOrder.length - 1) {
                this.currentTab = this.tabOrder[currentIndex + 1];
            } else {
                // 转换选择的值为API参数
                const apiParams = {
                    relationshipTags: this.selectedValues.对象.length > 0 ? this.selectedValues.对象.map((item) => this.valueMapping.对象[item]) : [],
                    occasionTags: this.selectedValues.场合.length > 0 ? this.selectedValues.场合.map((item) => this.valueMapping.场合[item]) : [],
                    genderTags: this.selectedValues.性别.length > 0 ? this.selectedValues.性别.map((item) => this.valueMapping.性别[item]) : [],
                    typeTags: this.selectedValues.类型.length > 0 ? this.selectedValues.类型.map((item) => this.valueMapping.类型[item]) : [],
                    ageTags: this.selectedValues.年龄.length > 0 ? this.selectedValues.年龄.map((item) => this.valueMapping.年龄[item]) : []
                };

                // 处理价格范围
                const priceRanges = this.selectedValues.价格;
                if (priceRanges.length > 0) {
                    apiParams.priceTags = priceRanges.map(range => this.valueMapping.价格[range]);
                }
                // 不设置默认价格，让后端处理默认值

                // 保存参数并跳转
                uni.setStorageSync('apiParams', apiParams);
                uni.navigateTo({
                    url: '/pages/browse/browse'
                });
            }
        },
        goPrevious() {
            const currentIndex = this.getTabIndex(this.currentTab);
            if (currentIndex > 0) {
                this.currentTab = this.tabOrder[currentIndex - 1];
            }
        },
        selectAllItems() {
           
            const currentOptions = this.options[this.currentTab];
            // 如果当前已经全部选中，则取消全选
            // const isAllSelected = currentOptions.every(item => this.selectedValues[this.currentTab].includes(item));
            // if (isAllSelected) {
            //     this.selectedValues[this.currentTab] = [];
            // } else {
            this.selectedValues[this.currentTab] = [...currentOptions];
            // }
            // 自动进入下一步
            this.goNext();
        },
        skip() {
            // 直接跳转到预览页面，不再进行下一步的标签切换
            // 使用当前已选的所有参数
            const apiParams = {
                relationshipTags: this.selectedValues.对象.length > 0 ? this.selectedValues.对象.map((item) => this.valueMapping.对象[item]) : [],
                occasionTags: this.selectedValues.场合.length > 0 ? this.selectedValues.场合.map((item) => this.valueMapping.场合[item]) : [],
                genderTags: this.selectedValues.性别.length > 0 ? this.selectedValues.性别.map((item) => this.valueMapping.性别[item]) : [],
                typeTags: this.selectedValues.类型.length > 0 ? this.selectedValues.类型.map((item) => this.valueMapping.类型[item]) : [],
                ageTags: this.selectedValues.年龄.length > 0 ? this.selectedValues.年龄.map((item) => this.valueMapping.年龄[item]) : []
            };
            
            // 处理已选择的价格范围（如果有）
            const priceRanges = this.selectedValues.价格;
            if (priceRanges.length > 0) {
                apiParams.priceTags = priceRanges.map(range => this.valueMapping.价格[range]);
            }
            
            // 保存参数并直接跳转到浏览页面
            uni.setStorageSync('apiParams', apiParams);
            uni.navigateTo({
                url: "/pages/browse/browse"
            });
        }
    }
}
</script>

<style lang="scss">
.select-container {
    min-height: 100vh;
    position: relative;
    padding-top: calc(150rpx + var(--status-bar-height, 0px)); /* Use CSS variable for status bar height */
    padding-bottom: 120rpx;
    background-image: #fff;
    background-size: 40rpx 40rpx;
}

.nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    height: calc(40rpx + var(--status-bar-height, 0px)); /* Use CSS variable for status bar height */
    padding: var(--status-bar-height, 0px) 30rpx 0; /* Add padding-top for status bar */
    background-color: #fff;
    z-index: 100;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

    .back-icon {
        font-size: 40rpx;
        color: #333;
        padding: 10rpx;
        z-index: 1;

        image {
            width: 32rpx;
            height: 32rpx;
            display: block;
        }
    }

    .title {
        position: absolute;
        left: 0;
        right: 0;
        text-align: center;
        font-size: 36rpx;
        font-weight: 500;
    }
}

.step-indicator {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0;
    background-color: transparent;
    width: 90%;
    margin: 0 auto;
    /* Remove margin-top as we've added padding-top to the container */

    .step-item {
        display: flex;
        align-items: center;
        position: relative;
        width: calc(100% / 6);
        justify-content: center;

        .step-dot {
            width: 30rpx;
            height: 30rpx;
            border-radius: 50%;
            background-color: #ddd;
            z-index: 1;
        }

        .step-line {
            position: absolute;
            height: 2rpx;
            background-color: #ddd;
            width: 100%;
            left: 50%;
            z-index: 0;
        }

        &:last-child {
            .step-line {
                display: none;
            }
        }

        &.completed {
            .step-dot,
            .step-line {
                background-color: #8B2A2A;
            }
        }

        &.active {
            .step-dot {
                background-color: #8B2A2A;
                width: 30rpx;
                height: 30rpx;
            }
        }
    }
}

.filter-tabs {
    display: flex;
    justify-content: space-between;
    background-color: transparent;
    padding: 20rpx 0;
    width: 90%;
    margin: 0 auto;

    .tab-item {
        width: calc(100% / 6);
        text-align: center;
        font-size: 32rpx;
        color: #333;
        padding: 12rpx 0;
        position: relative;

        &.active {
            color: #fff;
            background-color: #881B20;
            border-radius: 0;
        }
    }
}

.content {
    padding: 60rpx 30rpx;
    height: 900rpx;
    /* Remove margin-top as we've added padding-top to the container */

    .question {
        font-size: 36rpx;
        font-weight: 500;
        color: #333;
        text-align: center;
        margin-bottom: 40rpx;
    }
}

.options-container {
    .swipe-container {
        width: 100%;
        touch-action: pan-x;
    }
    .option-row {
        margin-bottom: 30rpx;
        display: flex;
        justify-content: center;

        &.two-columns {
            justify-content: space-between;

            .option-item {
                width: 48%;
            }
        }

        .option-item {
            width: 80%;
            height: 90rpx;
            background-color: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            color: #333;
            border-radius: 8rpx;

            &.selected {
                border: 2rpx solid #8B2A2A;
                color: #8B2A2A;
                background-color: rgba(139, 42, 42, 0.1);
            }
        }
    }
}
.select-all-btn {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 180rpx;
    color: #8B2A2A;
    font-size: 32rpx;
    text-decoration: underline;
    cursor: pointer;
    z-index: 1;
    text-align: center;
}

.bottom-actions {
    position: fixed;
    bottom: 60rpx;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;

    .back-btn {
        width: 80rpx;
        height: 80rpx;
        background-color: #8B2A2A;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 40rpx;

        image {
            width: 32rpx;
            height: 32rpx;
        }
    }


    .skip-btn {
        color: #8B2A2A;
        font-size: 32rpx;
        text-decoration: underline;
    }

    .next-btn {
        width: 80rpx;
        height: 80rpx;
        background-color: #8B2A2A;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 40rpx;

        image {
            width: 32rpx;
            height: 32rpx;
        }
    }
}

.progress-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 10rpx;
    background-color: #eee;

    .progress-inner {
        height: 100%;
        background-color: #8B2A2A;
        transition: width 0.3s;
    }
}

.page-controller {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30rpx;

    .page-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        border-radius: 50%;
        margin: 0 20rpx;

        &.disabled {
            opacity: 0.5;
            pointer-events: none;
        }

        image {
            width: 32rpx;
            height: 32rpx;
        }
    }

    .page-indicator {
        font-size: 28rpx;
        color: #666;
    }
}

.selected-items {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20rpx;
    margin-bottom: 30rpx;
    display: none;

    .selected-item {
        background-color: #8B2A2A;
        color: #fff;
        padding: 10rpx 20rpx;
        border-radius: 50rpx;
        font-size: 26rpx;
        margin-right: 20rpx;
        margin-bottom: 15rpx;
        display: flex;
        align-items: center;

        .remove-icon {
            margin-left: 10rpx;
            font-size: 28rpx;
            font-weight: bold;
        }
    }
}
</style>
